<template>
  <view class="st-u-moment st-bg-color-white">
    <view class="st-u-moment-item" v-for="(momentData,index) in momentDataList" :key="index">
      <!--    左侧-->
      <view class="post-left">
        <!--头像信息-->
        <u-avatar :src="momentData.ownerUserAvatar" @tap="$emit('avatarClick',momentData)" mode="circle"
                  :show-sex="!!genderResolve(momentData)" :sex-icon="gender[genderResolve(momentData)]" ></u-avatar>
        <slot name="left" v-bind:moment="momentData"></slot>
      </view>
      <!--右侧-->
      <view class="post_right">
        <view class="st-flex-align-between">
          <!--      昵称-->
          <text class="post-username">{{momentData.ownerUserNickname}}</text>
          <view>
            <slot name="rightAction"></slot>

            <!--     评论     chat-fill-->
            <u-icon name="chat" class="st-color-less" size="40" style="margin-right: 20rpx;" @click="commentClick(momentData)"></u-icon>
            <!--     点赞     thumb-up-fill-->
            <u-icon :name="momentData.isMeHasStared ? 'thumb-up-fill' : 'thumb-up'" class="st-color-less" :label="momentData.starCount" size="40"
                    style="margin-right: 20rpx;"
                    :style="{color: momentData.isMeHasStared ? '#fcbd71' : ''}"
                    @click="starOrCancel(momentData)"></u-icon>

          </view>
        </view>
        <!--        可以自定义插槽-->
        <slot name="rightSubTitle" v-bind:moment="momentData"></slot>
        <!--        昵称下方的文字区域 一般和自定义插槽 rightSubTitle 二选一即可-->
        <template>
          <view style="font-size: 26rpx; color: grey;" >
            <template v-for="(item,index) in rightSubTitleData(momentData)">
              <text class='iconfont' v-if="item.icon" :class="item.icon"></text>
              <text v-if="item.text" style="margin-right: 20rpx;">{{ item.text }}</text>
            </template>
          </view>
        </template>

        <!--      动态内容-->
        <view style="font-size: 26rpx;padding-top: 10rpx;padding-bottom: 10rpx;"><text>{{momentData.content}}</text></view>

        <!-- 相册 -->
        <view class="thumbnails">
          <view :class="momentData.momentPics.length === 1?'my-gallery':'thumbnail'" v-for="(image, index_images) in momentData.momentPics" :key="index_images">
            <u-image class="gallery_img" lazy-load mode="aspectFill" width="100%" height="100%" :src="image" @tap="previewImage(momentData.momentPics,index_images)"></u-image>
          </view>
        </view>

        <!--时间-->
        <view class="st-flex-align-between">
          <!--      发布时间-->
          <view class="timestamp" style="font-size: 25rpx;color: gainsboro;margin-top: 10rpx;"><text>{{$u.timeFrom($stDateTools.getDateObj(momentData.timeAt).getTime())}}</text></view>
          <!--     举报，不看他等     更多-->
          <u-icon name="more-dot-fill" class="st-color-less" size="40" style="margin-right: 20rpx;" @click="$emit('rightMoreClick',momentData)"></u-icon>
        </view>

        <!--点赞列表-->
        <view v-if="momentData.latestMomentStars && momentData.latestMomentStars.records.length > 0" class="st-flex star-box"
              style="margin-top: 20rpx;padding: 20rpx; background-color: #f3f3f5;" :class="{'star-box-border-bottom':momentData.latestCommentSubjects && momentData.latestCommentSubjects.records.length > 0}">
          <u-icon :name="momentData.isMeHasStared ? 'thumb-up-fill' : 'thumb-up'" class="st-color-less" size="40"
                  style="margin-right: 20rpx;"
                  :style="{color: momentData.isMeHasStared ? '#fcbd71' : ''}"
                  @click="starOrCancel(momentData)"></u-icon>
          <!-- 点赞人的头像-->
          <template v-for="(starItem,index) in momentData.latestMomentStars.records">
            <u-image @tap="starAvatarClick(momentData,starItem)"  :src="starItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;" :key="index">

            </u-image>
          </template>
          <view class="all-star" @tap="toAllStar(momentData)" v-if="momentData.starCount > 0">
            {{ momentData.starCount }}人赞过
            <u-icon class="more" name="arrow-right" :size="20"></u-icon>
          </view>
        </view>
        <!-- 评论-->
        <view class="comment-box" v-if="momentData.latestCommentSubjects && momentData.latestCommentSubjects.records.length > 0">
          <view class="item" v-for="(commentItem, index) in momentData.latestCommentSubjects.records" :key="index">
            <view class="st-flex">
              <u-image @tap="commentAvatarClick(momentData,commentItem)" :src="commentItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;">
              </u-image>
              <text class="nickname">{{ commentItem.ownerUserNickname }}</text>
            </view>
            <view class="text">
              <text class="content">{{ commentItem.content }}</text>
              <text class="reply" @tap="commentReplyClick(momentData,commentItem)">{{ commentItem.commentCount>0 ? commentItem.commentCount : ''}}回复<u-icon class="more" name="arrow-right" :size="20"></u-icon></text>
            </view>
          </view>
          <view class="all-comment" @tap="toAllComment(momentData)" v-if="momentData.commentCount > 0">
            共{{ momentData.commentCount }}条评论
            <u-icon class="more" name="arrow-right" :size="20"></u-icon>
          </view>
        </view>


      </view>

    </view>
    <stULoadmore ref="loadMore" :ready="loadMoment" @loadmore="loadMoment"></stULoadmore>
  </view>
</template>

<script>
/**
 * 动态列表组件
 */
import MomentUrl from '../../../../pc/MomentUrl'
import MomentStarUrl from '../../../../pc/MomentStarUrl.js'
import stULoadmore from '../../../../../../common/web/components/app/uni-app/uview/st-u-loadmore/st-u-loadmore.vue'
export default {
  components: {stULoadmore},
  props: {
    groupFlag:{
      type: String,
      default: ''
    },
    // 获取性别
    genderResolve: {
      type: Function,
      default: (moment)=>{
        let r = ''
        if(moment.ext){
          return moment.ext.genderDictValue
        }
        return r
      }
    },
    // 请求数据拦截处理
    formatResponseItem:{
      type: Function,
      default: (item)=>{
        return item
      }
    },
    // 右侧昵称下方文本数据,与slot=rightSubTitle 二选一即可
    // 返回数组元素应包含 {icon:'',text: ''}
    rightSubTitleData:{
      type: Function,
      default: (moment)=>{
        return []
      }
    },
    // 是否查询我的动态
    isMy: {
      type: Boolean,
      default:false
    },
    // 当前登录的用户id，如果不传默认使用 vuex_userInfo.id
    userId: {
      type: String
    }
  },
  data() {
    return {
      momentDataList: [],
      momentQuery:{
        current: 1,
        groupFlag: this.groupFlag
      },
    }
  },
  mounted(){
    //this.loadMoment()
  },
  methods: {
    previewImage(imageList, image_index) {
      let current = imageList[image_index];
      uni.previewImage({
        current: current,
        urls: imageList
      });
    },

    // 加载时刻动态数据
    loadMoment(refresh,callback=()=>{}) {
      if(!refresh && this.$refs.loadMore && !this.$refs.loadMore.canLoad()){
        if(callback){
          callback()
        }
        return
      }
      this.$http.get(this.isMy ? MomentUrl.myGetAvailablePage : MomentUrl.getAvailablePage,{params:this.momentQuery}).then(res => {
            if (this.momentQuery.current == 1) {
              this.momentDataList = []
            }
            res.data.records.forEach(item =>{
              this.momentDataList.push(this.formatResponseItem(item))
            });
            this.momentQuery.current = res.data.current + 1
            this.$refs.loadMore.loaded(res.data)
          }).catch((error)=>{
            this.$u.toast('抱歉系统出错误了')
            console.error(error)
            this.$refs.loadMore.loadError()
          })
          .finally(()=>{
            if(callback){
              callback()
            }
          })
    },
    // 重新加载
    refreshMoment(callback=()=>{}){
      this.momentQuery.current = 1
      this.loadMoment(true,callback)
    },
    // 在数据前添加一条，主要用于 moment 发布成功后不用去后台请求数据，直接添加一条即可
    prepend(moment){
      if (!moment) {
        return
      }
      this.momentDataList.unshift(this.formatResponseItem(moment))
    },
    // 在数据前添加一条评论，主要用于 comment 发布成功后不用去后台请求数据，直接添加一条即可
    prependStar(momentData,momentStar){
      if(!momentData.latestMomentStars){
        this.$set(momentData,'latestMomentStars',{records: []})
      }
      momentData.latestMomentStars.records.unshift(momentStar)
    },
    // 取消点赞使用，移除当前用户已点赞的数据
    removeStar(momentData){
      if(momentData.latestMomentStars){
        let userId = this.userId || this.vuex_userInfo.id
        let a = momentData.latestMomentStars.records
        for (let i = 0; i < a.length; i++) {
          if(a[i].ownerUserId == userId){
            a.splice(i,1)
            return
          }
        }
      }
    },
    /**
     * 给动态的某一个评论的回复数 加1
     * @param comment
     * @param num
     */
    commentItemReplyCountPlus(comment,momentId,num = 1){
      let momentData = this.getByMomentId(momentId)
      if (!momentData) {
        console.error('commentItemReplyCountPlus 没有找到数据，可能访问出现了问题，也可能到这里不需要处理，重新进入页面可能会正常，momentId=' + momentId)
        return
      }
      if(momentData.latestCommentSubjects && momentData.latestCommentSubjects.records.length > 0){
        momentData.latestCommentSubjects.records.forEach(item => {
          if(item.ownerUserId == comment.targetUserId){
            item.commentCount +=num
          }
        })
      }
    },
    // 在数据前添加一条评论，主要用于 comment 发布成功后不用去后台请求数据，直接添加一条即可
    prependComment(comment){
      let momentData = this.getByMomentId(comment.momentId || comment.subjectId)
      if (!momentData) {
        console.error('prependComment 没有找到数据，可能访问出现了问题，重新进入页面可能会正常，momentId=' + comment.momentId)
        return
      }
      if(!momentData.latestCommentSubjects){
        this.$set(momentData,'latestCommentSubjects',{records: []})
      }
      momentData.commentCount += 1
      momentData.latestCommentSubjects.records.unshift(comment)
    },
    getByMomentId(momentId){
      let filtered = this.momentDataList.filter(item => momentId == item.id)
      if(filtered.length > 0){
        return filtered[0]
      }
      return null;
    },
    // 点赞或取消
    starOrCancel(moment){
      if (moment.isMeHasStared) {
        // 最后面的参数 true 表示立即执行
        this.$u.debounce(()=>{this.doCancelStar(moment)}, 800,true)
      }else {
        this.$u.debounce(()=>{this.doStar(moment)}, 800,true)
      }
    },
    // 点赞发起请求
    doStar(moment){
      this.checkLogin().then(()=>{
        let data = {
          momentId: moment.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(MomentStarUrl.addStar,data).then((res)=>{
          moment.isMeHasStared = true
          moment.starCount += 1
          this.prependStar(moment,res.data)
        })
      })
    },
    // 取消点赞发起请求
    doCancelStar(moment){
      this.checkLogin().then(()=>{
        let data = {
          momentId: moment.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(MomentStarUrl.cancelStar,data).then(()=>{
          moment.isMeHasStared = false
          moment.starCount -= 1
          this.removeStar(moment)
        })
      })
    },
    // 点击评论事件,一般为添加一条评论
    commentClick(moment){
      this.$emit('commentClick',moment)
    },
    // 单条评论回复点击事件
    commentReplyClick(moment,commentItem){
      this.$emit('commentReplyClick', {moment,commentItem})
    },
    // 点击全部点赞事件
    toAllStar(moment){
      this.$emit('toAllStarClick',moment)
    },
    // 点击全部评论事件
    toAllComment(moment){
      this.$emit('toAllCommentClick',moment)
    },
    // 点击动态左侧头像事件
    avatarClick(moment){
      this.$emit('avatarClick',moment)
    },
    // 点击点赞区头像事件
    starAvatarClick(moment,starItem){
      this.$emit('starAvatarClick', {moment,starItem})
    },
    // 点击评论区头像事件
    commentAvatarClick(moment,commentItem){
      this.$emit('commentAvatarClick',{moment,commentItem})
    }
  }
}
</script>

<style scoped>

.st-u-moment-item {
  border-bottom: 1px solid #f2eeee;
  padding: 30rpx 20rpx;
  display: flex;
}
.st-u-moment-item .post_header {
  width: 80rpx !important;
  height: 80rpx !important;
  border-radius: 50%;
  margin-top: 8rpx;
}
.st-u-moment-item .post-username{
  font-size:32rpx;
  font-weight: 600;
  color: #36648B;
}
.st-u-moment-item .gallery_img {
  width: 100%;
  height: 100%
}

.st-u-moment-item  .post_right {
  font-size: 32rpx;
  display: table-cell;
  padding-left: 20rpx;
  width: 100%;
}

.st-u-moment-item .thumbnails {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.st-u-moment-item .thumbnails .thumbnail {
  width: 30%;
  height: 180rpx;
  margin: 4rpx;
  background: #757575;
  overflow: hidden;
}

.st-u-moment-item .my-gallery{
  width: 250rpx;
  height: 400rpx;
  margin: 4rpx;
  background: #757575;
  overflow: hidden
}
.st-u-moment-item .star-box{
  border-radius: 12rpx;
  margin-bottom: 12rpx;
}
</style>
<style lang="scss" scoped>
.st-u-moment-item .star-box-border-bottom{
  border-bottom: solid 2rpx $u-border-color;

}
.all-star {
  padding-left: 20rpx;
  display: flex;
  color: #5677fc;
  font-size: 26rpx;
  align-items: center;
  .more {
    margin-left: 3rpx;
  }
}


.comment-box {
  background-color: rgb(242, 242, 242);
  border-radius: 12rpx;
  .item {
    padding: 20rpx;
    border-bottom: solid 2rpx $u-border-color;
    .nickname {
      font-size: 26rpx;
      color: #999999;
      margin-left: 10rpx;
    }
    .text{
      margin-top: 10rpx;
      font-size: 26rpx;

      .reply{
        margin-left: 10rpx;
        color: #5677fc;
        font-size: 26rpx;
        .more {
          margin-left: 3rpx;
        }
      }
    }
  }
  .all-comment {
    padding: 20rpx;
    display: flex;
    color: #5677fc;
    align-items: center;
    font-size: 26rpx;
    .more {
      margin-left: 3rpx;
    }
  }
}
</style>